<?php
class ModelUserUser extends Model {
	public function addUser($data) {//额外补了3个字段：logcenter_permission、warehouse_permission、sales_area_id
		$this->db->query("INSERT INTO `" . DB_PREFIX . "user` SET username = '" . $this->db->escape($data['username']) . "', user_group_id = '" . (int)$data['user_group_id'] . "', salt = '" . $this->db->escape($salt = token(9)) . "', password = '" . $this->db->escape(sha1($salt . sha1($salt . sha1($data['password'])))) . "', fullname = '" . $this->db->escape($data['fullname']) . "', email = '" . $this->db->escape($data['email']) . "', contact_tel ='".$this->db->escape($data['tel'])."', image = '" . $this->db->escape($data['image']) . "', status = '" . (int)$data['status'] . "', date_added = NOW(), `logcenter_permission`='".$this->db->escape($data['logcenter_permission'])."', `warehouse_permission`='".$this->db->escape($data['warehouse_permission'])."', `sales_area_id`='".$this->db->escape($data['sales_area_id'])."'");

        $user_id = $this->db->getLastId();
        if(isset($data['recommended_code'])) {
            $this->db->query("UPDATE `" . DB_PREFIX . "user` SET recommended_code = '" . $this->db->escape($data['recommended_code']) . "' WHERE user_id = '" . (int)$user_id . "'");
        }
	}

	public function editUser($user_id, $data) {//额外补了3个字段：logcenter_permission、warehouse_permission、sales_area_id
		$this->db->query("UPDATE `" . DB_PREFIX . "user` SET username = '" . $this->db->escape($data['username']) . "', user_group_id = '" . (int)$data['user_group_id'] . "', fullname = '" . $this->db->escape($data['fullname']) . "', email = '" . $this->db->escape($data['email']) . "', contact_tel ='".$this->db->escape($data['tel'])."', image = '" . $this->db->escape($data['image']) . "', status = '" . (int)$data['status'] . "', `recommended_code`='".$this->db->escape($data['recommended_code'])."' , `logcenter_permission`='".$this->db->escape($data['logcenter_permission'])."', `warehouse_permission`='".$this->db->escape($data['warehouse_permission'])."', `sales_area_id`='".$this->db->escape($data['sales_area_id'])."' WHERE user_id = '" . (int)$user_id . "'");

		if ($data['password']) {
			$this->db->query("UPDATE `" . DB_PREFIX . "user` SET salt = '" . $this->db->escape($salt = token(9)) . "', password = '" . $this->db->escape(sha1($salt . sha1($salt . sha1($data['password'])))) . "' WHERE user_id = '" . (int)$user_id . "'");
		}
	}

	public function editPassword($user_id, $password) {
		$this->db->query("UPDATE `" . DB_PREFIX . "user` SET salt = '" . $this->db->escape($salt = token(9)) . "', password = '" . $this->db->escape(sha1($salt . sha1($salt . sha1($password)))) . "', code = '' WHERE user_id = '" . (int)$user_id . "'");
	}

	public function editCode($email, $code) {
		$this->db->query("UPDATE `" . DB_PREFIX . "user` SET code = '" . $this->db->escape($code) . "' WHERE LCASE(email) = '" . $this->db->escape(utf8_strtolower($email)) . "'");
	}

	public function deleteUser($user_id) {
		$this->db->query("DELETE FROM `" . DB_PREFIX . "user` WHERE user_id = '" . (int)$user_id . "'");
	}

	public function getUser($user_id) {
		$query = $this->db->query("SELECT *, (SELECT ug.name FROM `" . DB_PREFIX . "user_group` ug WHERE ug.user_group_id = u.user_group_id) AS user_group FROM `" . DB_PREFIX . "user` u WHERE u.user_id = '" . (int)$user_id . "'");

		return $query->row;
	}

	public function getUserByUsername($username) {
		$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "user` WHERE username = '" . $this->db->escape($username) . "'");

		return $query->row;
	}

	public function getUserByCode($code) {
		$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "user` WHERE code = '" . $this->db->escape($code) . "' AND code != ''");

		return $query->row;
	}

	public function getUsers($data = array()) {
        $sql = "SELECT * FROM `" . DB_PREFIX . "user` WHERE 1";

        if ('' != $data['name']){
            $sql .= " AND (`username` LIKE '%".$data['name']."%' OR `fullname` LIKE '%".$data['name']."%' OR `contact_tel` LIKE '%".$data['name']."%')";
        }
        if ('*' != $data['user_group_id'] && '' != $data['user_group_id']) {
            $sql .= " AND `user_group_id`='".intval($data['user_group_id'])."'";
        }
        if ('*' != $data['status'] && '' != $data['status']) {
            $sql .= " AND `status`='".intval($data['status'])."'";
        }

		$sort_data = array(
			'username',
			'fullname',
            'contact_tel',
			'user_group_id',
			'status',
			'date_added'
		);

		if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
			$sql .= " ORDER BY " . $data['sort'];
		} else {
			$sql .= " ORDER BY username";
		}

		if (isset($data['order']) && ($data['order'] == 'DESC')) {
			$sql .= " DESC";
		} else {
			$sql .= " ASC";
		}

		if (isset($data['start']) || isset($data['limit'])) {
			if ($data['start'] < 0) {
				$data['start'] = 0;
			}

			if ($data['limit'] < 1) {
				$data['limit'] = 20;
			}

			$sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
		}

		$query = $this->db->query($sql);

		return $query->rows;
	}

    public function getTotalUsers($data = array()) {
        $sql = "SELECT COUNT(*) AS total FROM `" . DB_PREFIX . "user` WHERE 1";
        if ('' != $data['name']){
            $sql .= " AND (`username` LIKE '%".$data['name']."%' OR `fullname` LIKE '%".$data['name']."%' OR `contact_tel` LIKE '%".$data['name']."%')";
        }
        if ('*' != $data['user_group_id'] && '' != $data['user_group_id']) {
            $sql .= " AND `user_group_id`='".intval($data['user_group_id'])."'";
        }
        if ('*' != $data['status'] && '' != $data['status']) {
            $sql .= " AND `status`='".intval($data['status'])."'";
        }

        $query = $this->db->query($sql);
        return $query->row['total'];
    }

	public function getTotalUsersByGroupId($user_group_id) {
		$query = $this->db->query("SELECT COUNT(*) AS total FROM `" . DB_PREFIX . "user` WHERE user_group_id = '" . (int)$user_group_id . "'");

		return $query->row['total'];
	}

	public function getTotalUsersByEmail($email) {
		$query = $this->db->query("SELECT COUNT(*) AS total FROM `" . DB_PREFIX . "user` WHERE LCASE(email) = '" . $this->db->escape(utf8_strtolower($email)) . "'");

		return $query->row['total'];
	}

	public function getUsersTp($data){
		$map['status'] = 1;
		$map['user_group_id'] = $data['user_group_id']?$data['user_group_id']:0;
		$map['fullname'] = array('like','%'.$data['sales_id_name'].'%');
		$map['recommended_code'] = array('like','%'.$data['recommended_code'].'%');
		$limit = $data['limit']?$data['limit']:20;

		$user_model = M('user');
		$user_data = $user_model
		->where($map)
		->limit($limit)
		->select();
		return $user_data;
	}

    /*
     * 获取仓库管理员PK
     * @author sonicsjh
     */
    public function getUserIdByWarehouseId($warehouseId) {
        $sql = "SELECT `user_id` FROM `".DB_PREFIX."user` WHERE `logcenter_permission`='".$warehouseId."' AND `logcenter_permission_level`='0'";
        $query = $this->db->query($sql);
        return $query->row;
    }

    public function getfullname($user_id){
        $sql="SELECT `fullname` FROM `".DB_PREFIX."user` WHERE `user_id`=".$user_id;
        $query = $this->db->query($sql);
        return $query->row;
    }
}
